#include "stm32f10x.h"                  // Device header
#include "OLED.h"
#include "Delay.h"
#include "led.h"
#include "Serial.h"
#include <string.h>


int main(void)
{
	Led_Init();
	OLED_Init();
	Serial_Init();
	
	Serial_SendString("AT\r\n");
	
	OLED_ShowString(1, 1, "Receive:");
	OLED_ShowString(3, 1, "Sleep:");
	
	uint8_t sleepOnFree = 0;
	OLED_ShowNum(3, 7, sleepOnFree, 1);

	uint16_t count = 0;
	OLED_ShowNum(4, 1, count, 10);
	
	char rxData[RX_BYTE_BUFFER_SIZE];
	while(1) {
		while (Serial_hasRxData()) {
			Serial_readRxData(rxData);
			OLED_ShowString(2, 1, "                ");
			OLED_ShowString(2, 1, rxData);
			if (strcmp(rxData, "on") == 0) {
				Led_On();
				Serial_SendString("OK\r\n");
			} else if (strcmp(rxData, "off") == 0) {
				Led_Off();
				Serial_SendString("OK\r\n");
			} else if (strcmp(rxData, "turn") == 0) {
				Led_Turn();
				Serial_SendString("OK\r\n");
			} else if (strcmp(rxData, "son") == 0) {
				sleepOnFree = 1;
				Serial_SendString("OK\r\n");
			} else if (strcmp(rxData, "soff") == 0) {
				sleepOnFree = 0;
				Serial_SendString("OK\r\n");
			} else {
				Serial_SendString("UNKNOW\r\n");
			}
		}
		count ++;
		OLED_ShowNum(4, 1, count, 10);
		OLED_ShowNum(3, 7, sleepOnFree, 1);
		
		if (sleepOnFree) {
			Delay_ms(100);
			// 延迟100毫秒后，如果还没有数据能够读取，则睡眠
			if (!Serial_hasRxData()) {
				__WFI();
			}
		}
	}
}
